/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-05
 * Time: 17:19
 */
public class Solution2 {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        }
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode ret = new ListNode();
        ListNode cur = ret;
        // 如果当前两个数相加结果大于10, 用 carry 保存大于 9 的部分
        boolean carry = false;
        while (cur1 != null || cur2 != null) {
            if (cur1 != null && cur2 != null) {
                cur.val = cur1.val + cur2.val;
            } else if (cur1 != null) {
                cur.val = cur1.val;
            } else {
                cur.val = cur2.val;
            }
            if (carry) {
                cur.val += 1;
                carry = false;
            }
            if (cur.val >= 10) {
                cur.val -= 10;
                carry = true;
            }
            if ((cur1 != null && cur1.next != null)
                    || (cur2 != null && cur2.next != null)) {
                cur.next = new ListNode();
            }
            if (cur1 != null) {
                cur1 = cur1.next;
            }
            if (cur2 != null) {
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        if (carry) {
            cur.val += 1;
        }
        return ret;
    }

    public static void main(String[] args) {
        MySingleList list1 = new MySingleList();
        list1.addLast(2);
        list1.addLast(4);
        list1.addLast(3);

        MySingleList list2 = new MySingleList();
        list2.addLast(5);
        list2.addLast(6);
        list2.addLast(4);


        ListNode node = addTwoNumbers(list1.head, list2.head);
        System.out.println();
    }
}
